package com.allen.app.common.domain;

import cn.hutool.core.util.StrUtil;
import com.allen.app.common.utils.Args;
import com.allen.app.common.utils.CheckObjectUtils;
import com.allen.app.common.utils.StringUtils;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
import lombok.Data;

/**
 * Description: 分页查询对象
 *
 * @author Limiaojun
 * @date 2019/3/29 17:12
 **/
@Data
public class PageDomain {

    public static final Long DEFAULT_PAGE = 1L;
    public static final Long DEFAULT_ROWS = 10L;
    /**最大查询5万条数据**/
    public static final Long MAX_ROWS = 50000L;

    /**
     * 当前页
     */
    public static final String PAGE = "page";
    /**
     * 每页多少条
     */
    public static final String PAGE_ROWS = "rows";
    /**
     * 排序字段
     */
    public static final String PAGE_SIDX = "sidx";
    /**
     * 排序方式
     */
    public static final String PAGE_SORT = "sort";


    @ApiModelProperty(value = "当前页(不传默认就不分页)")
    private Long page;

    @ApiModelProperty(value = "每页显示条数(最大会限制50000条)")
    private Long rows;

    @ApiModelProperty(value = "排序字段")
    private String sidx;

    @ApiModelProperty(value = "排序类型")
    private String sort;

    public void setRows(Long rows) {
        this.rows = (Objects.nonNull(rows) && rows > MAX_ROWS) ? MAX_ROWS : rows;
    }

    public String getOrderBy()
    {
        if (StrUtil.isEmpty(sidx) || StrUtil.isEmpty(sort))
        {
            return "";
        }
        String[] fieldArr = StrUtil.toUnderlineCase(sidx).split(",");
        String[] sortArr = StrUtil.toUnderlineCase(sort).split(",");
        Args.check(fieldArr.length == sortArr.length, "排序字段和类型数量不一致");

        StringBuilder sbl = new StringBuilder();
        for (int i = 0; i < fieldArr.length; i++) {
            Args.check(CheckObjectUtils.containsStr("asc,desc", sortArr[i]), "排序类型只能是asc or desc");
            sbl.append(fieldArr[i]).append(" ").append(sortArr[i]).append(",");
        }

        return StringUtils.removeLastChar(sbl.toString());
    }

}
